/*
 * @Descripttion:
 * @Author: cuidm
 * @Date: 2022-05-07 11:00:07
 * @LastEditors: cuidm
 * @LastEditTime: 2022-10-18 12:55:11
 */
import React, { useState, useEffect } from 'react';
import { Table, Space, Button, message } from 'antd';
import { CmdbContent, useModelAssociateType, Authorized } from '@/components';
import permission from '@/config/permission';
import cmdbres from '@/data/cmdbres';
import request, { exportFile } from '@/utils/request';
import CreateRelation from './createRelation';
import DeleteRelation from './deleteRelation';

const ResourceRelation = ({ cmModuleId, moduleInfo, info }) => {
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState({});
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const [{ associateType }] = useModelAssociateType();
    const [showCreateRelation, setShowCreateRelation] = useState(false);
    const [showDeleteRelation, setShowDeleteRelation] = useState(false);
    const columns = [
        {
            title: '模型数据关系ID',
            key: 'id',
            dataIndex: 'id',
            isShow: true,
            width: 80,
            copyable: true,
            ellipsis: true,
        },
        {
            title: '模型名称',
            key: 'destModuleName',
            dataIndex: 'destModuleName',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
        },
        {
            title: '实例名称',
            key: 'destResourceName',
            dataIndex: 'destResourceName',
            isShow: true,
            width: 140,
        },
        {
            title: '实例ID',
            key: 'destResourceId',
            dataIndex: 'destResourceId',
            isShow: true,
            width: 140,
        },
        {
            title: '关联类型',
            key: 'associateType',
            dataIndex: 'associateType',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => {
                return `${associateType?.[text] ?? '-'}(${text})`;
            },
        },
        {
            title: '源-目标约束',
            key: 'mapping',
            dataIndex: 'mapping',
            isShow: true,
            width: 120,
            copyable: true,
            ellipsis: true,
        },
        {
            title: '操作',
            fixed: 'right',
            width: 100,
            woIsSystem: 1,
            woIsHidden: 1,
            render: (text, record, index) => {
                return (
                    <Space key={record.cm_unid}>
                        <Authorized authority={permission.instanceRelation_delete} noMatch={null}>
                            <a
                                onClick={() => {
                                    setRow(record);
                                    setShowDeleteRelation(true);
                                }}
                            >
                                取消关联
                            </a>
                        </Authorized>
                    </Space>
                );
            },
        },
    ];

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        if (!(info && info.cm_unid)) {
            console.log('未获取到cm_unid:' + info);
            return;
        }
        setLoading(true);
        try {
            let res = await request({
                ...cmdbres.queryRelationData,
                params: {
                    id: info.cm_unid,
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                let arr = res.data.map((item, index) => {
                    let srcDefinition = item?.srcInfo?.moduleDefinition?.definition ?? {};
                    let destDefinition = item?.destInfo?.moduleDefinition?.definition ?? {};
                    let destModuleName = '';
                    if (cmModuleId == srcDefinition?.cmModuleId) {
                        destModuleName = `${destDefinition.moduleName || '-'}`;
                    } else {
                        destModuleName = `${srcDefinition.moduleName || '-'}`;
                    }
                    let srcResource = item.srcInfo.resource;
                    let destResource = item.destInfo.resource;
                    let destResourceId = '';
                    let destResourceName = '';
                    if (cmModuleId == srcResource.cm_module_id) {
                        destResourceId = `${destResource.cm_unid || '-'}`;
                        destResourceName = `${destResource.cm_name || '-'}`;
                    } else {
                        destResourceId = `${srcResource.cm_unid || '-'}`;
                        destResourceName = `${srcResource.cm_name || '-'}`;
                    }

                    return {
                        key: index,
                        ...item.moduleRelations,
                        ...item,
                        destModuleName,
                        destResourceId,
                        destResourceName,
                    };
                });
                setTableData(arr);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getTableData();
    }, [info]);

    const handleTableChange = (e) => {
        getTableData(e);
    };

    return (
        <div className="resource-catalog-pane">
            <div className="session-bar">
                <section style={{ width: '50%', float: 'left', padding: '5px 10px 15px 0' }}>
                    <Space>
                        <Authorized authority={permission.instanceRelation_add} noMatch={null}>
                            <Button
                                type="primary"
                                onClick={() => {
                                    setShowCreateRelation(true);
                                }}
                            >
                                新增关联
                            </Button>
                        </Authorized>
                        <Button
                            type="primary"
                            onClick={() => {
                                getTableData();
                            }}
                        >
                            刷新
                        </Button>
                    </Space>
                </section>
            </div>
            <Table
                columns={columns}
                loading={loading}
                dataSource={tableData}
                scroll={{ x: '100%' }}
                pagination={{
                    showSizeChanger: true,
                    showQuickJumper: {
                        goButton: <Button style={{ margin: '0 10px' }}>确定</Button>,
                    },
                    ...pagination,
                }}
                onChange={handleTableChange}
                hideSetting
            />
            {showCreateRelation && (
                <CreateRelation
                    onCreateFinish={getTableData}
                    visible={showCreateRelation}
                    setVisible={setShowCreateRelation}
                    cmModuleId={cmModuleId}
                    moduleInfo={moduleInfo}
                    cmInfo={info}
                    getTableData={getTableData}
                />
            )}

            <DeleteRelation
                onDeleteFinish={getTableData}
                visible={showDeleteRelation}
                setVisible={setShowDeleteRelation}
                info={row}
            />
        </div>
    );
};

export default ResourceRelation;
